/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.spider.rule.service.impl;

import me.zhengjie.spider.rule.domain.SpiderRule;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.spider.rule.repository.SpiderRuleRepository;
import me.zhengjie.spider.rule.service.SpiderRuleService;
import me.zhengjie.spider.rule.service.dto.SpiderRuleDto;
import me.zhengjie.spider.rule.service.dto.SpiderRuleQueryCriteria;
import me.zhengjie.spider.rule.service.mapstruct.SpiderRuleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 雨来
* @date 2023-07-07
**/
@Service
@RequiredArgsConstructor
public class SpiderRuleServiceImpl implements SpiderRuleService {

    private final SpiderRuleRepository spiderRuleRepository;
    private final SpiderRuleMapper spiderRuleMapper;

    @Override
    public PageResult<SpiderRuleDto> queryAll(SpiderRuleQueryCriteria criteria, Pageable pageable){
        Page<SpiderRule> page = spiderRuleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(spiderRuleMapper::toDto));
    }

    @Override
    public List<SpiderRuleDto> queryAll(SpiderRuleQueryCriteria criteria){
        return spiderRuleMapper.toDto(spiderRuleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SpiderRuleDto findById(Long ruleId) {
        SpiderRule spiderRule = spiderRuleRepository.findById(ruleId).orElseGet(SpiderRule::new);
        ValidationUtil.isNull(spiderRule.getRuleId(),"SpiderRule","ruleId",ruleId);
        return spiderRuleMapper.toDto(spiderRule);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(SpiderRule resources) {
        int hasCount = spiderRuleRepository.countByWebIdAndFieldCode(resources.getWebId(), resources.getFieldCode());
        if (Objects.equals(hasCount, 0)) {
            resources.setDeletedFlag(false);
            spiderRuleRepository.save(resources);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(SpiderRule resources) {
        int hasCount = spiderRuleRepository.countByWebIdAndFieldCodeAndRuleIdNot(resources.getWebId(), resources.getFieldCode(), resources.getRuleId());
        if (Objects.equals(hasCount, 0)) {
            SpiderRule spiderRule = spiderRuleRepository.findById(resources.getRuleId()).orElseGet(SpiderRule::new);
            ValidationUtil.isNull( spiderRule.getRuleId(),"SpiderRule","id",resources.getRuleId());
            spiderRule.copy(resources);
            spiderRuleRepository.save(spiderRule);
            return true;
        }
        return false;
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long ruleId : ids) {
            spiderRuleRepository.deleteById(ruleId);
        }
    }

    @Override
    public void download(List<SpiderRuleDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SpiderRuleDto spiderRule : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("网站名称", spiderRule.getWebId());
            map.put("字段名称", spiderRule.getFieldName());
            map.put("字段编码", spiderRule.getFieldCode());
            map.put("规则", spiderRule.getRule());
            map.put("删除状态", spiderRule.getDeletedFlag());
            map.put("备注", spiderRule.getRemark());
            map.put("更新时间", spiderRule.getUpdateTime());
            map.put("创建时间", spiderRule.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}